package study.service.attachment;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import study.domain.attachment.Attachment;
import study.domain.user.User;
import study.repository.attachment.AttachmentRepository;

@Service
public class AttachmentService {

	@Value("#{applicationProperties['attachment.root.path']}")
	private String attachmentRootPath;

	@Value("#{applicationProperties['attachment.expires']}")
	private long attachmentExpires;

	@Resource(name = "attachmentRepository")
	private AttachmentRepository attachmentRepository;

	@Resource(name = "attachmentImageService")
	private AttachmentImageService attachmentImageService;

	public File getAttachmentFile(String filePath) {
		return new File(attachmentRootPath, filePath);
	}

	public long getAttachmentExpires() {
		return attachmentExpires;
	}

	public List<Attachment> findAll(List<String> attachmentIds, Long userId, String category) {
		return attachmentRepository.findAllByUser_UserIdAndCategoryAndIdIn(userId, category,
				attachmentIds);
	}

	/**
	 * 첨부파일을 저장한다.
	 */
	@Transactional(readOnly = false)
	public Attachment addAttachment(Attachment attachment) {
		return attachmentRepository.save(attachment);
	}

	/**
	 * 첨부파일을 저장하고 반환한다.
	 * 
	 * @param user
	 * @param category
	 * @param file
	 */
	public Attachment addAttachment(User user, String category, String groupId, MultipartFile file) {
		Attachment attachment = new Attachment();
		attachment.setId(Attachment.generateUuid());
		attachment.setGroupId(groupId);
		attachment.setUser(user);
		attachment.setCategory(category);
		attachment.setCreatedDate(new Date());
		attachment.setFilename(file.getOriginalFilename());
		attachment.setFilesize(file.getSize());

		File dest = new File(attachmentRootPath, attachment.getFilePath());
		try {
			FileUtils.forceMkdir(dest.getParentFile());
			file.transferTo(dest);
			if (attachment.isImage()) {
				attachmentImageService.resize(dest, attachmentRootPath, attachment);
			}
			return addAttachment(attachment);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 첨부파일을 삭제한다.
	 * 
	 * @param id
	 */
	public void removeAttachment(String id) {
		attachmentRepository.delete(id);
	}
}
